package com.googlecode.spruce.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public abstract class AbstractDao<K extends Serializable, E extends Serializable> implements GenericDao<K, E>
{
    @Autowired
    private SessionFactory sessionFactory;

    private Class<? extends Serializable> genericType;

    public AbstractDao(final Class<? extends Serializable> genericType)
    {
        this.genericType = genericType;
    }

    public void setSessionFactory(final SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    protected Session getSession()
    {
        return this.sessionFactory.getCurrentSession();
    }

    @Override
    @SuppressWarnings("unchecked")
    public E findByID(final K id)
    {
        return (E) this.getSession().get(genericType, id);
    }

    @Override
    public void save(final E item)
    {
        this.getSession().save(item);
    }

    @Override
    public void delete(final E item)
    {
        this.getSession().delete(item);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<E> getAll()
    {
        return this.getSession().createCriteria(genericType).list();
    }

}
